package com.fairylove.rpc.transport.socket.server;

import com.fairylove.rpc.entity.Message;
import com.fairylove.rpc.entity.RpcRequest;
import com.fairylove.rpc.entity.RpcResponse;
import com.fairylove.rpc.factory.ThreadPoolFactory;
import com.fairylove.rpc.handler.RequestHandler;
import com.fairylove.rpc.serializer.CommonSerializer;
import com.fairylove.rpc.transport.utils.ObjectReader;
import com.fairylove.rpc.transport.utils.ObjectWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

import static com.fairylove.rpc.serializer.CommonSerializer.DEFAULT_SERIALIZER;

public class SocketServer {
      private static  final Logger logger = LoggerFactory.getLogger(SocketServer.class);

      private  ExecutorService threadPool;
      private  String host;
      private  Integer port;
      private final CommonSerializer commonSerializer;
      private RequestHandler requestHandler = new RequestHandler();

      public SocketServer(String host,int port){
          this(host,port,DEFAULT_SERIALIZER);
      }
      public SocketServer(String host,int port,Integer serializer){
          this.host = host;
          this.port = port;
          this.commonSerializer = CommonSerializer.getByCode(serializer);
          threadPool = ThreadPoolFactory.createDefaultThreadPool("socket-rpc-server");

      }

      public SocketServer(){
          this(DEFAULT_SERIALIZER);
      }
      public SocketServer(int code){
          this.commonSerializer = CommonSerializer.getByCode(code);
      }
      public void start(){
          //创建socket对象并绑定ip和端口

          try(ServerSocket serverSocket = new ServerSocket()) {
              Socket socket;
              serverSocket.bind(new InetSocketAddress(host,port));
              logger.info("服务器启动");
              //通过accept方法监听客户端请求
              while((socket = serverSocket.accept()) != null){
                  logger.info("client connected :{},{}",socket.getInetAddress(),socket.getPort());
                  threadPool.execute(new SocketRequestHandlerRunnable(socket, requestHandler, commonSerializer));
//
              }
              threadPool.shutdown();
          } catch (IOException e) {
              logger.info("occur exception" + e);
          }
      }


}
